#!/bin/bash

# Flutter 通用脚本部署工具
# 作用：将 playtrue3 项目的通用脚本部署到其他 Flutter 项目

echo "🚀 Flutter 通用脚本部署工具"
echo "======================================"

# 检查参数
if [ $# -eq 0 ]; then
    echo "❌ 用法: $0 <目标Flutter项目路径>"
    echo ""
    echo "例如:"
    echo "  $0 /path/to/my_flutter_project"
    echo "  $0 ../another_flutter_project"
    echo ""
    exit 1
fi

TARGET_DIR="$1"
SOURCE_DIR="$(cd "$(dirname "${BASH_SOURCE[0]}")" && pwd)"

echo "📁 源目录: $SOURCE_DIR"
echo "📁 目标目录: $TARGET_DIR"
echo ""

# 检查目标目录
if [ ! -d "$TARGET_DIR" ]; then
    echo "❌ 目标目录不存在: $TARGET_DIR"
    exit 1
fi

# 检查是否为 Flutter 项目
if [ ! -f "$TARGET_DIR/pubspec.yaml" ]; then
    echo "❌ 目标目录不是 Flutter 项目: $TARGET_DIR"
    echo "请确保目标目录包含 pubspec.yaml 文件"
    exit 1
fi

echo "✅ 目标目录验证通过"

# 显示项目信息
if [ -f "$TARGET_DIR/pubspec.yaml" ]; then
    PROJECT_NAME=$(grep "^name:" "$TARGET_DIR/pubspec.yaml" | cut -d' ' -f2)
    echo "📄 目标项目: $PROJECT_NAME"
fi

echo ""
echo "📦 准备部署以下脚本："
echo "   🧹 flutter_clean.command - 清理项目"
echo "   📦 flutter_pub_get.command - 获取依赖"
echo "   🔄 flutter_reset.command - 完整重置"
echo "   📱 flutter_build_apk.command - Android 打包"
echo "   🍎 flutter_build_ios_release.command - iOS 发布配置"
echo "   🔧 fix_ios_simulator.command - 模拟器修复"
echo "   🛠️  fix_permissions.sh - 权限修复"
echo ""

# 询问是否继续
read -p "是否继续部署？(Y/n): " CONFIRM
if [[ $CONFIRM =~ ^[Nn]$ ]]; then
    echo "❌ 用户取消部署"
    exit 0
fi

echo ""
echo "🔄 开始部署脚本..."

# 复制脚本文件
SCRIPTS_COPIED=0
SCRIPTS_FAILED=0

copy_script() {
    local script_name="$1"
    if [ -f "$SOURCE_DIR/$script_name" ]; then
        cp "$SOURCE_DIR/$script_name" "$TARGET_DIR/"
        if [ $? -eq 0 ]; then
            echo "   ✅ $script_name"
            ((SCRIPTS_COPIED++))
        else
            echo "   ❌ $script_name (复制失败)"
            ((SCRIPTS_FAILED++))
        fi
    else
        echo "   ⚠️  $script_name (源文件不存在)"
    fi
}

# 复制所有脚本
copy_script "flutter_clean.command"
copy_script "flutter_pub_get.command"
copy_script "flutter_reset.command"
copy_script "flutter_build_apk.command"
copy_script "flutter_build_ios_release.command"
copy_script "fix_ios_simulator.command"
copy_script "fix_permissions.sh"

echo ""
echo "🔑 设置执行权限..."
cd "$TARGET_DIR"
chmod +x flutter_*.command fix_*.sh fix_*.command 2>/dev/null

echo ""
echo "🎉 部署完成！"
echo "======================================"
echo "📊 部署统计："
echo "   ✅ 成功: $SCRIPTS_COPIED 个脚本"
if [ $SCRIPTS_FAILED -gt 0 ]; then
    echo "   ❌ 失败: $SCRIPTS_FAILED 个脚本"
fi

echo ""
echo "📋 已部署的脚本："
cd "$TARGET_DIR"
ls -la flutter_*.command fix_*.sh fix_*.command 2>/dev/null | while read line; do
    echo "   $line"
done

echo ""
echo "💡 使用说明："
echo "   1. 直接双击 .command 文件执行"
echo "   2. 或在终端中运行: ./脚本名称"
echo "   3. 这些脚本适用于任何 Flutter 项目"

echo ""
echo "🔧 推荐使用顺序："
echo "   1. flutter_reset.command - 首次使用或遇到问题时"
echo "   2. flutter_build_apk.command - Android 打包"
echo "   3. flutter_build_ios_release.command - iOS 打包前配置"

echo ""
echo "⏰ 部署完成时间: $(date)"
echo ""
